<template>
    <el-dialog
            :title="isSysOperation? (!dataForm.id ? '新增' : '修改') : '个人信息'"
            :close-on-click-modal="false"
            :append-to-body="true"
            :visible.sync="visible">
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
                 label-width="80px">
            <el-form-item label="登录账号" prop="userName">
                <el-input v-model="dataForm.userName" placeholder="登录帐号" :disabled="!isSysOperation"></el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="alias">
                <el-input v-model="dataForm.alias" placeholder="用户名"></el-input>
            </el-form-item>
            <el-form-item label="头像" prop="img">
                <img-upload v-model="dataForm.img" >
                    <el-avatar fit="contain" :src="dataForm.img || imgSys" style="width: 30px;height: 30px"></el-avatar>
                </img-upload>
            </el-form-item>
            <el-form-item v-if="isSysOperation" label="密码" prop="password" :class="{ 'is-required': !dataForm.id }">
                <el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
            </el-form-item>
            <el-form-item v-if="isSysOperation" label="确认密码" prop="comfirmPassword" :class="{ 'is-required': !dataForm.id }">
                <el-input v-model="dataForm.comfirmPassword" type="password" placeholder="确认密码"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="dataForm.email" placeholder="邮箱" :disabled="!isSysOperation"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="dataForm.mobile" placeholder="手机号"></el-input>
            </el-form-item>
            <el-form-item label="简介" prop="remark">
                <el-input v-model="dataForm.remark" placeholder="简介"></el-input>
            </el-form-item>
            <el-form-item label="地址" prop="addr">
                <el-input v-model="dataForm.addr" placeholder="地址"></el-input>
            </el-form-item>
            <el-form-item label="学校" prop="school">
                <el-input v-model="dataForm.school" placeholder="学校"></el-input>
            </el-form-item>
            <el-form-item v-if="isSysOperation" label="角色" size="mini" prop="roleIdList">
                <el-checkbox-group v-model="dataForm.roleIdList">
                    <el-checkbox v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{ role.roleName }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item v-if="isSysOperation" label="状态" size="mini" prop="status">
                <el-radio-group v-model="dataForm.status">
                    <el-radio :label="0">禁用</el-radio>
                    <el-radio :label="1">正常</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
    </el-dialog>
</template>

<script>
    import {isEmail, isMobile} from '@/utils/validate'
    import imgUpload from '@/components/img/img-upload'

    export default {
        data() {
            let validatePassword = (rule, value, callback) => {
                if (!this.dataForm.id && !/\S/.test(value)) {
                    callback(new Error('密码不能为空'))
                } else {
                    callback()
                }
            }
            let validateComfirmPassword = (rule, value, callback) => {
                if (!this.dataForm.id && !/\S/.test(value)) {
                    callback(new Error('确认密码不能为空'))
                } else if (this.dataForm.password !== value) {
                    callback(new Error('确认密码与密码输入不一致'))
                } else {
                    callback()
                }
            }
            let validateEmail = (rule, value, callback) => {
                if (!isEmail(value)) {
                    callback(new Error('邮箱格式错误'))
                } else {
                    callback()
                }
            }
            let validateMobile = (rule, value, callback) => {
                if (value && value.trim()!='' && !isMobile(value)) {
                    callback(new Error('手机号格式错误'))
                } else {
                    callback()
                }
            }
            return {
                visible: false,
                roleList: [],
                dataForm: {
                    id: 0,
                    userName: '',
                    alias: '',
                    password: '',
                    comfirmPassword: '',
                    salt: '',
                    email: '',
                    mobile: '',
                    img: '',
                    remark: '',
                    addr: '',
                    school: '',
                    roleIdList: [],
                    status: 1
                },
                dataRule: {
                    userName: [
                        {required: true, message: '用户名不能为空', trigger: 'blur'}
                    ],
                    password: [
                        {validator: validatePassword, trigger: 'blur'}
                    ],
                    comfirmPassword: [
                        {validator: validateComfirmPassword, trigger: 'blur'}
                    ],
                    email: [
                        {required: true, message: '邮箱不能为空', trigger: 'blur'},
                        {validator: validateEmail, trigger: 'blur'}
                    ],
                    mobile: [
                        {validator: validateMobile, trigger: 'blur'}
                    ]
                },
                //是否系统维度操作 - 区别个人中心和系统操作
                isSysOperation:true,
                //系统默认图片
                imgSys:'https://blog-yunglee.oss-cn-chengdu.aliyuncs.com/2021-06-15/0ec2865d-38fa-4b49-891c-77ef95ee757f.png',
            }
        },
        components:{imgUpload},
        methods: {
            /**
             * 增加type参数，用于区分系统修改和个人用户修改 1、个人修改
             * @param id
             * @param type
             */
            init(id,type) {
                this.dataForm.id = id || 0;
                this.isSysOperation = (type !== 1);

                if(this.isSysOperation) {
                    this.$api.Role.select().then((data) => {
                        this.roleList = data && data.code === 0 ? data.list : []
                    }).then(() => {
                        this.visible = true
                        this.$nextTick(() => {
                            this.$refs['dataForm'].resetFields()
                        })
                    }).then(() => {
                        if (this.dataForm.id) {
                            this.$api.User.info(this.dataForm.id).then((data) => {
                                if (data && data.code === 0) {
                                    this.dataForm.userName = data.user.username
                                    this.dataForm.alias = data.user.alias
                                    this.dataForm.salt = data.user.salt
                                    this.dataForm.email = data.user.email
                                    this.dataForm.mobile = data.user.mobile
                                    this.dataForm.roleIdList = data.user.roleIdList
                                    this.dataForm.status = data.user.status
                                    this.dataForm.img = data.user.img
                                    this.dataForm.remark = data.user.remark
                                    this.dataForm.addr = data.user.addr
                                    this.dataForm.school = data.user.school
                                }
                            })
                        }
                    })
                }else{
                    this.visible = true
                    this.$nextTick(() => {
                        this.$refs['dataForm'].resetFields()
                    })
                    if (this.dataForm.id) {
                        this.$api.User.info(this.dataForm.id).then((data) => {
                            if (data && data.code === 0) {
                                this.dataForm.userName = data.user.username
                                this.dataForm.alias = data.user.alias
                                this.dataForm.salt = data.user.salt
                                this.dataForm.email = data.user.email
                                this.dataForm.mobile = data.user.mobile
                                this.dataForm.roleIdList = data.user.roleIdList
                                this.dataForm.status = data.user.status
                                this.dataForm.img = data.user.img
                                this.dataForm.remark = data.user.remark
                                this.dataForm.addr = data.user.addr
                                this.dataForm.school = data.user.school

                            }
                        })
                    }
                }
            },
            // 表单提交
            dataFormSubmit() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        let data = {
                            'userId': this.dataForm.id || undefined,
                            'username': this.dataForm.userName,
                            'alias': this.dataForm.alias,
                            'password': this.dataForm.password,
                            'salt': this.dataForm.salt,
                            'email': this.dataForm.email,
                            'mobile': this.dataForm.mobile,
                            'status': this.dataForm.status,
                            'roleIdList': this.dataForm.roleIdList,
                            'img': this.dataForm.img,
                            'remark': this.dataForm.remark,
                            'addr': this.dataForm.addr,
                            'school': this.dataForm.school,
                        };

                        let resultAction;
                        if (!this.dataForm.id) {
                            resultAction = this.$api.User.save(data);
                        } else {
                            resultAction = this.$api.User.update(data);
                        }

                        resultAction.then((res) => {
                            if (res && res.code === 0) {
                                this.$message({
                                    message: '操作成功',
                                    type: 'success',
                                    duration: 1500,
                                    onClose: () => {
                                        this.visible = false
                                        this.$emit('refreshDataList')
                                    }
                                })

                                //若是个人修改维护个人数据
                                if(!this.isSysOperation){
                                    this.$store.commit('updateUserInfo', data);
                                    sessionStorage.setItem('userInfo', JSON.stringify(data || '{}'));
                                }
                                
                            } else {
                                this.$message.error(res.msg)
                            }
                        })
                    }
                })
            }
        }
    }
</script>
